﻿using Cofe.Core.Interfaces;
using Cofe.Core.Property;
using Cofe.Core.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Cofe.Core.Actions
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFE)]
    public class CopyStream : ITransferHelper
    {
        public TransferMode GetSupportedMode(ICofeSystemInfo[] entries, ICofeDirectoryInfo fromm, ICofeDirectoryInfo too)
        {
            if (entries == null || entries.Length == 0)
                return TransferMode.None;

            if (!(too.Properties.Behaviors.IsPropertySupported(CofeDirectoryProperties.CreateAsync)))
                return TransferMode.None;

            foreach (var entry in entries)
                if (!(entry.Is<IStreamInfo>()))
                    return TransferMode.None;

            return TransferMode.Copy;
        }

        public async Task<TransferMode> TransferAsync(TransferMode mode, ICofeSystemInfo[] entries, ICofeDirectoryInfo fromm, ICofeDirectoryInfo too,
            IProgress<ProgressEventArgs> progress, CancellationToken cts)
        {
            if (mode == TransferMode.Copy && GetSupportedMode(entries, fromm, too) == TransferMode.Copy)
            {
                foreach (var entry in entries)
                {
                    var destEntry = await too.CreateAsync<IStreamInfo>(entry.Type, entry.Name);

                    using (var srcStream = (await entry.As<IStreamInfo>().OpenReadAsync()).Stream)
                    using (var destStream = (await destEntry.OpenWriteAsync()).Stream)
                        StreamUtils.CopyStream(srcStream, destStream);
                }

                return TransferMode.Copy;
            }
            else throw new NotSupportedException();
        }

        public Task<TransferMode> RenameAsync(TransferMode mode, ICofeSystemInfo entry, ICofeDirectoryInfo fromm,
         string newName, IProgress<ProgressEventArgs> progress, CancellationToken cts)
        {
            throw new NotImplementedException();
        }


        private IEntryConstructor _entryConstructor = null;
        public ITransferHelper[] _allHelpers = null;

        public IEntryConstructor EntryConstructor
        {
            get { return _entryConstructor ?? CofeServices.ServiceLocater.FindService<IEntryConstructor>(); }
            set { _entryConstructor = value; }
        }
        public ITransferHelper[] AllHelpers
        {
            get { return _allHelpers ?? CofeServices.ServiceLocater.FindAllServices<ITransferHelper>().ToArray(); }
            set { _allHelpers = value; }
        }
    }
}
